﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using Bookvar.ObjectModel;
using Bookvar.UI.Adorners;
using Bookvar.UI.Commands;

namespace Bookvar.UI
{
    public class ResourceItemsControl : ListBox
    {
        public ResourceItemsControl()
        {
            Binding binding = new Binding( "HasItems" );
            binding.Source = this;
            binding.Converter = new BooleanToVisibilityConverter();

            SetBinding( VisibilityProperty, binding );
        }

        protected override DependencyObject GetContainerForItemOverride()
        {
            return new ResourceItem();
        }

        protected override bool IsItemItsOwnContainerOverride(object item)
        {
            return (item is ResourceItem);
        }

        protected override void OnSelectionChanged(SelectionChangedEventArgs e)
        {
            base.OnSelectionChanged( e );

            foreach ( Resource addedItem in e.AddedItems )
            {
                ResourceItem item = ItemContainerGenerator.ContainerFromItem( addedItem ) as ResourceItem;
                if ( item != null )
                {
                    AdornerLayer adornerLayer = AdornerLayer.GetAdornerLayer( item );
                    if ( adornerLayer != null )
                    {
                        ResizingAdorner resizingAdorner = new ResizingAdorner( item );
                        adornerLayer.Add( resizingAdorner );
                    }
                }
            }

            foreach ( Resource removedItem in e.RemovedItems )
            {
                ResourceItem item = ItemContainerGenerator.ContainerFromItem( removedItem ) as ResourceItem;
                if ( item != null )
                {
                    AdornerLayer adornerLayer = AdornerLayer.GetAdornerLayer( item );
                    if ( adornerLayer != null )
                    {
                        foreach ( Adorner adorner in adornerLayer.GetAdorners( item ) )
                        {
                            if ( adorner is ResizingAdorner )
                            {
                                adornerLayer.Remove( adorner );
                            }
                        }

                    }
                }
            }
        }

        protected override void OnKeyDown(KeyEventArgs e)
        {
            if ( e.Key == Key.Delete )
            {
                if ( SelectedIndex >= 0)
                {
                    BookvarCommands.DeleteResource.Execute( SelectedItem, this );
                }
                e.Handled = true;
            }

            base.OnKeyDown( e );
        }
    }
}
